class SwarmController < ApplicationController
  
  def create
    @cl=Catelog.find(:all,:order=>"id asc").collect{|c|[c.title,c.id]}
  end
  
  def list
    @catelogs=Catelog.find(:all)
    if(!params[:id].nil?)then condition="catelog_id = "+params[:id] end
    @result_pages,@swarm=paginate(:swarms,:order=>"creation_time",:conditions=>condition,:per_page=>2)
  end
  
  def show_one
    
    @swarm=Swarm.find(:first,:conditions=>"url = '"+params[:id]+"'")

    tags=Array.new
    @swarm[:tags].split('|').each do |tag|
      tags << Tag.find(tag).name
    end
    @swarm[:tags]=tags.join(',')
  end
  
  def save
    require 'digest/md5'
    tags=params[:swarm][:tags].split(',')
    tags_id=''
    Tag.transaction do
      if(!tags.nil? && tags.size!=0)
        
        tags.each do |tag|
          t=Tag.find_by_name(tag)
          if(t.nil?)
            t2=Tag.create(:id=>'null',:name=>tag,:num=>1)
            tags_id << t2.id.to_s+'|'
          else
            t.num+=1
            t.save
            tags_id << t.id.to_s+'|'
          end
        end
        
      end
      params[:swarm][:tags]=tags_id
      t=Time.new
      new_url=(Digest::MD5).new(t.to_s+session.session_id.to_s).to_s
      pic_url=(Digest::MD5).new(t.to_s+'pic_url'+session.session_id.to_s).to_s
      Swarm.save(params[:swarm],new_url,pic_url)
      
      flash[:notice]="you have created a swarm successly!"
      redirect_to :controller=>"swarm",:action=>"show_one",:id=>new_url
    end
  end
  
  def search
    
      @result_pages,@result_search=paginate(:swarms,:order=>"id",:conditions=>["title like ? or description like ? and public <> 2","%"+params[:content_search]+"%","%"+params[:content_search]+"%"])

    if(@result_search.nil?)
      flash[:notice]="sorry,no result!"
      redirect_to :controller=>"/swarm",:action=>"list"
    end
  end
  def search_by_tag
    @result_pages,@result_search=paginate(:swarms,:order=>"id",:conditions=>["tags like ?","%"+params[:id]+"|%"])
  end
  
  def join_swarm
    require 'digest/md5'
    t=Time.new
    new_url=(Digest::MD5).new(t.to_s+session.session_id.to_s).to_s
    combination=params[:join_swarm].join("|")
    Swarm.create(
                 :id=>'null',
    :title=>"joinedSwarm",
    :description=>"joinedSwarm",
    :catelog_id=>0,
    :contact_info=>combination,
    :url=>new_url,
    :creation_time=>t,
    :pic_url=>"null.jpg",
    :public=>2,
    :tags=>""
    )
    
    redirect_to '/webgui/index?server='+(request.protocol << request.host_with_port)+"/"+new_url+"/"
  end
  
end
